package com.woniu.springbootrbac.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.springbootrbac.util.Result;
import com.woniu.springbootrbac.vo.PerVo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class LoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authentication);
        LoginUser user = (LoginUser)authentication.getPrincipal();
        List<PerVo> menuList = user.getMenuList();
        response.setContentType("application/json;charset=utf-8");
        String string = new ObjectMapper().writeValueAsString(Result.ok().data("menuList", menuList));
        response.getWriter().println(string);
    }
}
